import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/card_details_entity.dart';
import 'package:nyh_motorcade_app/entity/driver_info_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CardDetailsController extends GetxController {
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  String companyId = "";
  String cardId = "";
  CardDetailsEntity? cardDetailsEntity;
  List<DriverInfoItem> driverInfoList = [];
  bool permissionTransferCard = false;

  @override
  Future<void> onReady() async {
    companyId = await SPUtils.getString(SPUtils.COMPANY_ID);
    permissionTransferCard = await SPUtils.getBool(SPUtils.PERMISSION_TRANSFER_CARD);
    cardId = Get.arguments ?? "";
    getCardDetails();
  }

  Future<void> onRefresh() async {
    getCardDetails();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getCardDetails();
  }

  void goBackHomePage() {
    Get.until((route) => Get.currentRoute == Routes.main);
  }

  Future<void> goToEditCardInfoPage() async {
    if (cardDetailsEntity == null) {
      return;
    }
    dynamic date = await Get.toNamed(Routes.addCard, arguments: {Constant.PARAM_ENTITY: cardDetailsEntity, Constant.PARAM_IS_RETURN: true});
    if (date != null) {
      multiState = MultiState.loading;
      update();
      getCardDetails();
    }
  }

  Future<void> goToBindDriverPage() async {
    if (cardDetailsEntity == null) {
      return;
    }
    dynamic data = await Get.toNamed(Routes.bindDriver, arguments: {
      Constant.PARAM_TYPE: Constant.CARD_BIND_DRIVER,
      Constant.PARAM_SOURCE_ID: cardDetailsEntity!.id ?? "",
    });
    if (data != null) {
      multiState = MultiState.loading;
      update();
      getCardDetails();
    }
  }

  Future<void> goToRapidTransferPage(String? id, String? name, double? amount) async {
    dynamic data = await Get.toNamed(Routes.rapidTransfer, arguments: {
      Constant.PARAM_RAPID_TRANSFER_FROM: Constant.RAPID_TRANSFER_FROM_CARD,
      Constant.PARAM_ACCOUNT_ID: id,
      Constant.PARAM_ACCOUNT_NAME: name ?? "",
      Constant.PARAM_ACCOUNT_AMOUNT: amount ?? 0.0,
    });
    if (data != null) {
      multiState = MultiState.loading;
      update();
      getCardDetails();
    }
  }

  Future<void> goToCardCashFlowPage(String? id) async {
    Get.toNamed(
      Routes.cashFlow,
      arguments: {
        "sourceId": id,
        "accountType": Constant.CARD,
      },
    );
  }

  Future<void> goToDriverDetailsPage(String? id) async {
    Get.toNamed(Routes.driverDetails, arguments: id);
  }

  void getCardDetails() {
    httpManager.post(
      Get.context,
      HttpAddress.GET_CARD_DETAILS,
      {
        "superId": companyId,
        "id": cardId,
      },
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          }
          multiState = MultiState.fail;
          update();
          return;
        }
        cardDetailsEntity = CardDetailsEntity().fromJson(data);
        driverInfoList = cardDetailsEntity!.driverInfo ?? [];
        if (refreshController.isRefresh) {
          refreshController.refreshCompleted();
        }
        multiState = MultiState.success;
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        }
        multiState = MultiState.fail;
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        }
        multiState = MultiState.error;
        update();
      },
    );
  }

  void unboundDriver(String? driverId) {
    httpManager.post(
      Get.context,
      HttpAddress.UNBOUND_CARD_DRIVER,
      {"cardId": cardId, "driverId": driverId},
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is bool) {
          if (!data) {
            ToastUtils.toast("解绑失败");
            return;
          }
          ToastUtils.toast("解绑成功");
          driverInfoList.removeWhere((element) {
            return element.id == driverId;
          });
          multiState = driverInfoList.isNotEmpty ? MultiState.success : MultiState.empty;
          update();
        }
      },
    );
  }
}
